#import "Common.h"
#import "DataType.h"
#import "BtnGold.h"
#import "LayerBuy.h"

@implementation BtnGold

-(id)init
{
	if ((self = [super init]))
	{
		CCSprite* item = [CCSprite spriteWithFile:@"btn-buygold.png"];
		CCSprite* itemDown = [CCSprite spriteWithFile:@"btn-buygold.png"];
		itemDown.color = ccGRAY;
		
		CCMenuItemSprite* menuItem = [CCMenuItemSprite itemFromNormalSprite:item selectedSprite:itemDown target:self selector:@selector(callMenu)];

		[menuItem runAction:
		 [CCRepeatForever actionWithAction:
			[CCSequence actions:
			 [CCDelayTime actionWithDuration:1],
			 [CCScaleTo actionWithDuration:0.1 scale:1.1],
			 [CCScaleTo actionWithDuration:0.1 scale:1],
			 [CCScaleTo actionWithDuration:0.1 scale:1.05],
			 [CCScaleTo actionWithDuration:0.1 scale:1],
			 [CCDelayTime actionWithDuration:0.3],	NULL]]];
		
		CCMenu* menu = [CCMenu menuWithItems:menuItem, NULL];
		menu.position = CGPointZero;
		[self addChild:menu];
		
		// star
		CCSpriteFrameCache *cache = [CCSpriteFrameCache sharedSpriteFrameCache];
		[cache addSpriteFramesWithFile:@"splashstar.plist"];
		CCTexture2D* tex = [[CCTextureCache sharedTextureCache] addImage:@"splashstar.png"];
		
		CCSprite* star = [CCSprite spriteWithSpriteFrameName:@"splashstar01.png"];
		star.position = ccp(15,15);
		star.visible = false;
		
		CCSpriteBatchNode* spriteBatch = [CCSpriteBatchNode batchNodeWithTexture:tex];
		[spriteBatch addChild:star];
		[self addChild:spriteBatch];
		
		NSMutableArray* animFrames = [NSMutableArray arrayWithCapacity:12];
		for(int i = 1; i <= 12; i++)
		{
			[animFrames addObject:[cache spriteFrameByName:[NSString stringWithFormat:@"splashstar%02d.png", i]]];
		}
		
		CCAnimation *animation = [CCAnimation animationWithFrames:animFrames];
		[star runAction:
		 [CCRepeatForever actionWithAction:
			[CCSequence actions:
			 [CCDelayTime actionWithDuration:1.4],
			 [CCShow action],
			 [CCAnimate actionWithDuration:0.3 animation:animation restoreOriginalFrame:NO],
			 [CCHide action], NULL]]];
		
		mGoldCount = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%s", commaprint(gGlobalData.gold)]
										fontName:gFontName
										fontSize:12];
		mGoldCount.color = ccYELLOW;
		mGoldCount.position = ccp(0,-30);
		[self addChild:mGoldCount];
		
		[self scheduleUpdate];
	}
	return self;
}

-(void)update:(ccTime)dt
{
	mGoldCount.string = [NSString stringWithFormat:@"%s", commaprint(gGlobalData.gold)];
}

-(void)callMenu
{
	[[SimpleAudioEngine sharedEngine] playEffect:SOUND_BTN01];
	[self.parent onExit];
	LayerBuy* buy = [[[LayerBuy alloc] initWithParent:(CCLayer*)self.parent] autorelease];
	CCScene* scene = [[CCDirector sharedDirector] runningScene];
	[scene addChild:buy z:50000];
}

@end
